/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package br.gov.cemaden.library.dao.pcds;

import br.gov.cemaden.library.dao.GenericDao;
import br.gov.cemaden.library.interfaces.pcds.AquisicaoInterface;
import java.util.Date;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;

/**
 *
 * @author alan
 */
public class AquisicaoDao extends GenericDao implements AquisicaoInterface{
    
    Session session;
    
    public AquisicaoDao(Session session){
        this.session = session;
    }
    
    public Long countByRede(Long idRede, Date datahora) throws HibernateException{       
        
        Number quantity;
        Query query = session.createSQLQuery(
            "SELECT COUNT(dt) FROM (" +
                " SELECT max(datahora) as dt, e.id_estacao FROM pcds.pcds_aquisicao a" +
                " INNER JOIN pcds.pcds_estacao e on a.id_estacao = e.id_estacao" +
                " WHERE e.id_rede = :id_rede" +
                " GROUP BY e.id_estacao" +
            ") AS x WHERE dt > :datahora"
        )
        .setParameter("id_rede", idRede)
        .setTimestamp("datahora", datahora);
                  
        quantity = (Number) query.uniqueResult();
            
        return quantity.longValue();
    }
    
}
